package com.yyplatform.frontend.infra.advice;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.yyplatform.frontend.infra.exception.ErrorCode;
import com.yyplatform.frontend.infra.exception.ServiceException;
import com.yyplatform.frontend.infra.model.RestResponse;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-13
 */
@Slf4j
@RestControllerAdvice
@AllArgsConstructor
public class ExceptionHandlerAdvice {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    public RestResponse handleRenException(ServiceException ex) {
        return RestResponse.of(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public RestResponse handleDuplicateKeyException(DuplicateKeyException ex) {
        return RestResponse.of(ErrorCode.DB_RECORD_EXISTS);
    }

    @ExceptionHandler(Exception.class)
    public RestResponse handleException(Exception ex) {
        log.error(ex.getMessage(), ex);

        saveLog(ex);

        RestResponse r = RestResponse.of(ErrorCode.UNKNOW_ERROR.getCode(), ex.getMessage());


        return r;
    }

    /**
     * 保存异常日志
     */
    private void saveLog(Exception ex) {
        // todo

    }


}
